package com.atguigu.ossservice.service.impl;

import com.aliyun.oss.OSSClient;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.ossservice.utils.ConstantPropertiesUtil;
import com.atguigu.servicebase.handler.GuliException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    //上传文件
    @Override
    public String uploadFileOss(MultipartFile file) {
        //获取阿里云存储相关常量
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endPoint = ConstantPropertiesUtil.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String uploadUrl = null;
        try {
            //判断oss实列是否存在，如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endPoint,accessKeyId,accessKeySecret);
            //填写本地文件的完整路径，如果未指定本地路径，则默认从示例程序所属项目对应的
            //获取输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String fileName = file.getOriginalFilename();

            //UUID+filename   1111111+02.jpg
            fileName = UUID.randomUUID().toString().replace("-", "") + fileName;
            //2021/04/02/001.jpg
            String filepath= new DateTime().toString("yyyy/MM/dd");
            fileName=filepath+"/"+fileName;

            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName,fileName,inputStream);
            //关闭ossclient
            ossClient.shutdown();
            //获取url地址   https://guli-file210402.oss-cn-beijing.aliyuncs.com/girl.jpg

            uploadUrl="https://" + bucketName + "." + endPoint + "/" + fileName;
            return uploadUrl;
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(20001,"上传文件失败");
        }

    }
}
